package com.gitee.mars.tourserver.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.mars.tourserver.constant.Constant;
import com.gitee.mars.tourserver.entity.ScenicArea;
import com.gitee.mars.tourserver.entity.TourHotel;
import com.gitee.mars.tourserver.entity.TourRoute;
import com.gitee.mars.tourserver.entity.TravelStrategy;
import com.gitee.mars.tourserver.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wq
 * @version 1.0
 * @date 2021/04/11 17:26
 */
@Component
public class TourClawerManager {

    @Resource
    private HttpUtils httpUtils;


    /**
     * 获取路线
     *
     * @return List<TourRoute>
     */
    public List<TourRoute> getTourRoute() {
        List<TourRoute> list = new ArrayList<>();
        for (int i = 1; i <= 29; i++) {
            System.out.println("正在获取第" + i + "页数据");
            String data = HttpUtils.doGet("https://zt.dujia.qunar.com/tejia/new_tejia_get_list.php?callback=jQuery172015341909999214232_1618364935991&dep=%E5%85%A8%E9%83%A8&arr=&type=&date=&displaynum=15&chan=freetravel&tf=&from=pc&_=1618365053204&page=" + i);
            System.out.println(data);
            String str1 = data.substring(0, data.indexOf("("));
            String str2 = data.substring(str1.length() + 1);
            String result = str2.substring(0, str2.indexOf(")"));
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("ret").equals(Constant.ONE)) {
                JSONArray headData = jsonObject.getJSONArray("headData");
                for (int i1 = 0; i1 < headData.size(); i1++) {
                    TourRoute tourRoute = new TourRoute();
                    String ttsid = headData.getJSONObject(i1).getString("ttsid");
                    tourRoute.setTtSid(ttsid);
                    Double marketPrice = headData.getJSONObject(i1).getDouble("market_price");
                    double ceil = Math.ceil(marketPrice);
                    tourRoute.setMarketPrice((int) ceil);
                    Double price = headData.getJSONObject(i1).getDouble("price");
                    double ceil1 = Math.ceil(price);
                    tourRoute.setPrice((int) ceil1);
                    String stitle = headData.getJSONObject(i1).getString("stitle");
                    tourRoute.setName(stitle);
                    String title = headData.getJSONObject(i1).getString("title");
                    tourRoute.setTitle(title);

                    String imgurl = headData.getJSONObject(i1).getString("imgurl");
                    tourRoute.setImgUrl(imgurl);

                    String linkurl = headData.getJSONObject(i1).getString("linkurl");
                    tourRoute.setDetailUrl(linkurl);
                    tourRoute.setCreateTime(new Date());
                    tourRoute.setUpdateTime(new Date());
                    list.add(tourRoute);
                }
            }

        }
        return list;
    }


    public List<TourHotel> getTourHotel(String city) {
        System.out.println("正在获取城市:" + city);
        try {
            List<TourHotel> list = new ArrayList<>();
            String data = httpUtils.doPost("https://hotel.qunar.com/napi/hotHotelList?size=50&fromDate=2021-04-14&toDate=2021-04-15&time=1618371733057&city=" + city);
            if (StringUtils.isNotEmpty(data)) {
                JSONArray parseArray = JSONObject.parseArray(data);
                if (parseArray.size() > 0) {
                    for (int i = 0; i < parseArray.size(); i++) {
                        TourHotel tourHotel = new TourHotel();
                        String name = parseArray.getJSONObject(i).getString("name");
                        tourHotel.setName(name);

                        String price = parseArray.getJSONObject(i).getString("price");
                        tourHotel.setPrice(price);
                        String gpoint = parseArray.getJSONObject(i).getString("gpoint");
                        tourHotel.setGPoint(gpoint);
                        String hotPoi = parseArray.getJSONObject(i).getString("hotPoi");
                        tourHotel.setHotLocation(hotPoi);
                        String hotPoiDistance = parseArray.getJSONObject(i).getString("hotPoiDistance");
                        if (StringUtils.isNotEmpty(hotPoiDistance)) {
                            tourHotel.setHotLocationDistance(Integer.parseInt(hotPoiDistance));
                        }
                        Integer commentCount = parseArray.getJSONObject(i).getInteger("commentCount");
                        tourHotel.setCommentCount(commentCount);
                        String imgUrl = parseArray.getJSONObject(i).getString("imageid");
                        tourHotel.setImgUrl(imgUrl);

                        String locationInfo = parseArray.getJSONObject(i).getString("locationInfo");
                        tourHotel.setLocationInfo(locationInfo);

                        String phoneNumber = parseArray.getJSONObject(i).getString("phoneNumber");
                        tourHotel.setPhone(phoneNumber);

                        String designStyles = parseArray.getJSONObject(i).getString("designStyles");
                        tourHotel.setDesignStyles(designStyles);

                        String score = parseArray.getJSONObject(i).getString("score");
                        tourHotel.setScore(score);
                        tourHotel.setUpdateTime(new Date());
                        tourHotel.setCreateTime(new Date());
                        list.add(tourHotel);
                    }
                }
                return list;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取路由攻略
     */
    public List<TravelStrategy> getTravelStrategy() {
        List<TravelStrategy> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            System.out.println("正在获取第" + i + "页数据");
            String url = "https://travel.qunar.com/travelbook/list.htm?order=hot_heat&page=" + i;
            Connection.Response response = null;
            try {
                response = Jsoup.connect(url).timeout(10 * 1000000)
                        .execute();
                String body = response.body();
                Document document = Jsoup.parse(body);
                Elements elements = document.getElementsByClass("list_item ");
                for (Element element : elements) {
                    TravelStrategy travelStrategy = new TravelStrategy();
                    String headImg = element.getElementsByClass("imgf").attr("src");
                    travelStrategy.setAvatar(headImg);

                    Elements elementPic = element.getElementsByClass("pic");
                    if (elementPic.size() > 0) {
                        Element element2 = elementPic.get(0);
                        String imgUrl = element2.select("img").attr("src");
                        travelStrategy.setImgUrl(imgUrl);
                    }

                    String username = element.getElementsByClass("imgf").attr("title");
                    travelStrategy.setUsername(username);

                    String description = element.getElementsByClass("tit").get(0).select("a").text();
                    travelStrategy.setDescription(description);

                    String date = element.getElementsByClass("date").get(0).text();
                    travelStrategy.setStartTime(date);

                    String days = element.getElementsByClass("days").get(0).text();
                    travelStrategy.setTotalDays(days);

                    Elements elementFee = element.getElementsByClass("fee");
                    if (elementFee.size() > 0) {
                        String fee = elementFee.get(0).text();
                        travelStrategy.setTotalFee(fee);

                    }

                    Elements elementPeople = element.getElementsByClass("people");
                    if (elementPeople.size() > 0) {
                        String people = elementPeople.get(0).text();
                        travelStrategy.setTravelType(people);
                    }

                    Elements elementTrip = element.getElementsByClass("trip");
                    if (elementTrip.size() > 0) {
                        String trip = elementTrip.get(0).text();
                        travelStrategy.setTips(trip);
                    }

                    Elements places = element.getElementsByClass("places");
                    String placeOne = "";
                    if (places.size() > 0) {
                        String placesStr = places.get(0).text();
                        if (places.size() > 1) {
                            placeOne = places.get(1).text();
                        }
                        travelStrategy.setTravelTheWay(placesStr);
                    }

                    Elements arrow = element.getElementsByClass("arrow");
                    if (arrow.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        sb.append(placeOne);
                        for (Element element1 : arrow) {
                            sb.append(element1.text());
                        }
                        travelStrategy.setTravelTrip(sb.toString());
                    }

                    travelStrategy.setCreateTime(new Date());
                    travelStrategy.setUpdateTime(new Date());
                    list.add(travelStrategy);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;

    }


    /**
     * 获取景点数据
     *
     * @param city city
     * @return List<ScenicArea>
     * @throws UnsupportedEncodingException
     */
    public List<ScenicArea> acquireScenicArea(String city) throws UnsupportedEncodingException {
        List<ScenicArea> list = new ArrayList<>();
        int page = 3;
        String encodeData = URLEncoder.encode(city, "utf-8");
        for (int i = 1; i <= page; i++) {
            System.out.println("正在获取" + city + "第" + i + "页数据");
            String url = "https://piao.qunar.com/ticket/list.htm?region=&from=mpl_search_suggest&keyword=" + encodeData + "&page=" + page;
            try {
                Connection.Response response = Jsoup.connect(url).timeout(10 * 1000000)
                        .execute();
                String body = response.body();
                Document document = Jsoup.parse(body);
                Elements elements = document.getElementsByClass("sight_item_detail clrfix");
                for (Element element : elements) {
                    ScenicArea scenicArea = new ScenicArea();
                    String name = element.select("h3 a").text();
                    scenicArea.setName(name);

                    Elements level = element.getElementsByClass("level");
                    if (level.size() > 0) {
                        Element element1 = level.get(0);
                        scenicArea.setLevel(element1.text());
                    }


                    Elements elements1 = element.getElementsByClass("address color999");
                    if (elements1.size() > 0) {
                        Element element1 = elements1.get(0);
                        String areaData = element1.select("span").text();
                        scenicArea.setLocation(areaData);
                    }


                    Elements price = element.getElementsByClass("sight_item_price");
                    if (price.size() > 0) {
                        Element element1 = price.get(0);
                        String priceData = element1.select("em").text();
                        if (StringUtils.isNotEmpty(priceData)) {
                            scenicArea.setPrice(Double.valueOf(priceData));
                        }
                    }

                    Elements elements2 = element.getElementsByClass("intro color999");
                    if (elements2.size() > 0) {
                        Element element1 = elements2.get(0);
                        String intro = element1.text();
                        if (StringUtils.isNotEmpty(intro)) {
                            scenicArea.setDescription(intro);
                        }
                    }

                    Elements elements3 = element.getElementsByClass("sight_item_sold-num");
                    if (elements3.size() > 0) {
                        Element element1 = elements3.get(0);
                        String sold = element1.select("span").text();
                        if (StringUtils.isNotEmpty(sold)) {
                            scenicArea.setSold(Integer.parseInt(sold));
                        }
                    }
                    Element element1 = element.select("img").get(0);
                    Elements imgOpacityLoad = element1.getElementsByClass("img_opacity load");
                    String img = imgOpacityLoad.attr("data-original");
                    scenicArea.setCoverPic(img);
                    scenicArea.setStatus(1);
                    scenicArea.setCreateTime(new Date());
                    scenicArea.setUpdateTime(new Date());
                    list.add(scenicArea);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

}
